package com.chixing.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.commons.MD5Util;
import com.chixing.commons.ServerResponse;
import com.chixing.commons.TokenUtil;
import com.chixing.mapper.CompanyManageMapper;
import com.chixing.mapper.PersonCenterMapper;
import com.chixing.pojo.CompanyManage;
import com.chixing.pojo.LoginPerson;
import com.chixing.pojo.PersonCenter;
import com.chixing.service.IPersonCenterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 个人中心表 服务实现类
 * </p>
 *
 * @author Jason Marslyon
 * @since 2022-10-04
 */
@Service
public class PersonCenterServiceImpl  implements IPersonCenterService {
    @Autowired
    private PersonCenterMapper personCenterMapper;

    @Autowired
    private CompanyManageMapper companyManageMapper;

    @Override
    public ServerResponse getById(Integer person) {
        PersonCenter personCenter = personCenterMapper.selectById(person);
        if (personCenter == null) {
            return ServerResponse.fail("查询用户",null);
        }
        else {
            return ServerResponse.success("查询用户成功",personCenter);
        }
    }

//    @Override
//    public ServerResponse save(PersonCenter personCenter) {
//
//        int rows = personCenterMapper.insert(personCenter);
//        if (rows>0) {
//            return ServerResponse.success("注册成功", personCenter);
//        }else {
//            return ServerResponse.fail("插入失败", 0);
//        }
//    }
@Override
public ServerResponse save(PersonCenter personCenter) {
    String loginPassoword = personCenter.getPersonPassword();
    String md5password = MD5Util.md5PassWord(loginPassoword);
    personCenter.setPersonPassword(md5password);
    int rows = personCenterMapper.insert(personCenter);
    if (rows>0) {
        return ServerResponse.success("注册成功", personCenter);
    }else {
        return ServerResponse.fail("插入失败", 0);
    }
}

//    //    ============================== 登录功能 =========================
//    @Override
//    public PersonCenter userCheckLogin(Long personTel, String personPassword) {
//        QueryWrapper<PersonCenter> personCenterQueryWrapper = new QueryWrapper<>();
//        personCenterQueryWrapper.eq("person_tel",personTel);
//        personCenterQueryWrapper.eq("person_password",personPassword);
//        PersonCenter personCenter = personCenterMapper.selectOne(personCenterQueryWrapper);//查询符合以上要求的一个结果
//        System.out.println(personCenter);
//        return personCenter;
//    }


//    登录token
@Override
public ServerResponse loginToken(PersonCenter personCenter) {
    //1. DB 验证用户名与密码
    QueryWrapper<PersonCenter> wrapper =  new QueryWrapper<>();
    wrapper.eq("person_tel",personCenter.getPersonTel());
    wrapper.eq("person_password",personCenter.getPersonPassword());


    PersonCenter loginUser = personCenterMapper.selectOne(wrapper);
    System.out.println("Service查询到的登录账户：" + loginUser);

    String token = null;
    if(loginUser !=null) {
        //2. JWT创建token
        LoginPerson loginPerson =  new LoginPerson(loginUser.getPersonId(),loginUser.getPersonName());
        token = TokenUtil.getToken(loginPerson);
        System.out.println("=============token==="+token);
        System.out.println("service token:" + token);
        return ServerResponse.success("impl登录成功", token);
    }else
        return ServerResponse.fail("impl登录失败",null);
}
    @Override
    public ServerResponse getByPersonal(Integer personalId) {
        PersonCenter personCenter = personCenterMapper.selectById(personalId);
        return ServerResponse.success("成功",personCenter);
    }

    //根据personId获取用户名字
    @Override
    public PersonCenter getPerName(Integer personId) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("person_id",personId);
        //        根据personId查得结果
        List<PersonCenter> personList = personCenterMapper.selectList(wrapper);
        System.out.println(" personCenterImpl-getPerName>>>>>"+ personList.get(0));//获取list第一条信息
        PersonCenter personCenter = personList.get(0);
        System.out.println("==============PersonCenterServiceImpl-getPerName==================");

        return personCenter;
    }

    @Override
    public ServerResponse updatePersonCenter(PersonCenter personCenter,Integer id) {
        PersonCenter personCenterSql = personCenterMapper.selectById(id);
        personCenterSql.setPersonName(personCenter.getPersonName());
        personCenterSql.setPersonJobStatus(personCenter.getPersonJobStatus());//身份
        personCenterSql.setText1(personCenter.getText1());//求职状态
        personCenterSql.setPersonGender(personCenter.getPersonGender());
        personCenterSql.setPersonBirthday(personCenter.getPersonBirthday());

        int update = personCenterMapper.updateById(personCenterSql);
        if(update>0){
            System.out.println(personCenterSql);
            return ServerResponse.success("成功",null);
        }
        return ServerResponse.fail("失败",null);
    }

    @Override
    public ServerResponse update(PersonCenter personCenter,String token) {
        LoginPerson loginPerson = TokenUtil.parseToken(token);
        System.out.println("**************************55555555555555555555*********"+loginPerson);
        Integer id = loginPerson.getPersonId();
        PersonCenter personCenters = personCenterMapper.selectById(id);
        personCenters.setPersonName(personCenter.getPersonName());
        personCenters.setPersonAge(personCenter.getPersonAge());
        personCenters.setPersonGender(personCenter.getPersonGender());
        personCenters.setPersonBirthday(personCenter.getPersonBirthday());
        personCenters.setPersonUsername(personCenter.getPersonUsername());

        //  将页面获取的password进行加密再在数据库中查
        String passoword = personCenter.getPersonPassword();
        String md5password = MD5Util.md5PassWord(passoword);

        personCenters.setPersonPassword(md5password);
        personCenters.setPersonTel(personCenter.getPersonTel());
        personCenters.setPersonJobStatus(personCenter.getPersonJobStatus());
        personCenters.setPersonCreateTime(LocalDate.now());
        personCenters.setPersonId(id);
        int personCenterUpdate =personCenterMapper.updateById(personCenters);

        return ServerResponse.success(">>>>>>>",personCenterUpdate);

    }

    @Override
    public PersonCenter checkLogin(PersonCenter personCenter) {
        QueryWrapper<PersonCenter> wrapper = new QueryWrapper<>();
        wrapper.eq("person_tel",personCenter.getPersonTel()).
                eq("person_password",personCenter.getPersonPassword());
        return personCenterMapper.selectOne(wrapper);
    }


//    @Autowired
//    Pespper personCenterMapper;
//
//    @Override
//    public PersonCenter checkLogin(Long telno, String password) {
//        List<PersonCenter> personCenters = personCenterMapper.selectList(null);
//        for (PersonCenter personCenter:personCenters) {
//            if(telno.equals(personCenter.getPersonTel()) && password.equals(personCenter.getPersonPasswoed()))
//                return personCenter;
//        }
//        return null;
//    }

    /**
     *获取所有人的姓名
     * @return
     */
    @Override
    public List<String> getAllManageName() {
        List<CompanyManage> companyManages = companyManageMapper.selectList(null);
        List<String> personNames = new ArrayList<>();
        for (CompanyManage companyManage:companyManages) {
            personNames.add(companyManage.getManageName());
        }
        return personNames;
    }

    @Override
    public Boolean sendMessage(String phone, String code, Map<String, Object> codeMap) {
        /**
         * 连接阿里云：
         *
         * 三个参数：
         * regionId 不要动，默认使用官方的
         * accessKeyId 自己的用户accessKeyId
         * accessSecret 自己的用户accessSecret
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou", "LTAI5tGq5iYtQFL2UDxy4JFp", "8h07WsOUwEu1lPs5OXQncOnH9CEoZC");
        IAcsClient client = new DefaultAcsClient(profile);
        // 构建请求：
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        // 自定义参数：
        System.out.println("ali:"+phone);
        request.putQueryParameter("PhoneNumbers", phone);// 手机号
        request.putQueryParameter("SignName", "阿里云短信测试");// 短信签名
        request.putQueryParameter("TemplateCode", "SMS_154950909");// 短信模版CODE
        // 构建短信验证码
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(codeMap));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public List<String> getAllUsername() {
        List<PersonCenter> personCenters = personCenterMapper.selectList(null);
        List<String> personNames = new ArrayList<>();
        for (PersonCenter person:personCenters) {
            personNames.add(person.getPersonName());
        }
        return personNames;
    }


}
